import { useForm } from 'antd/es/form/Form'
import {
  memo,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react'
import {
  Button,
  DatePicker,
  Drawer,
  DrawerProps,
  Form,
  Input,
  Select,
  Space,
  Spin,
  Table,
  Modal,
} from 'antd'
import {
  QueryObserverResult,
  RefetchOptions,
  RefetchQueryFilters,
} from 'react-query'
import {
  IFormRef,
  ILawsRef,
  IPage,
  IRoleRestFillRefHandler,
  ISelectMutiRef,
} from '../../../types'
import {
  IBeef,
  useAddBeef,
  useUpdateBeefById,
  useGetAllBeefTypeMap,
  useGetById,
  useRemoveById,
  useGetByBeefId,
} from '../../../service/beef/beef-service'
import UnitSelect from '../../../components/unit-list-select'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import TextArea from 'antd/es/input/TextArea'
import {
  IUploadImgRefHandler,
  UploadImage,
} from '../../../components/upload-img'
import BeefTypeSelect from '../../../components/beef-type-select'
import DsrFrom from './beef-dsr'
import SqUnitSelect from '../../../components/squnit-select'

import { TableContainer } from '../../../csscomponents/base'

dayjs.locale('zh-cn')

type IBeefFormParams = {
  beef?: IBeef
  open: boolean
  isEdit: number
  onRef: React.MutableRefObject<IFormRef | undefined>
  openFn: (open: boolean) => void
  setUpdate: React.Dispatch<React.SetStateAction<IBeef | undefined>>
  refetch?: <TPageData>(
    options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined
  ) => Promise<QueryObserverResult<IPage<IBeef>, unknown>>
} & DrawerProps

const BeefForm = ({ beef, onRef, ...props }: IBeefFormParams) => {
  const [form] = useForm()
  //单位的引用
  const unitRef = useRef<ILawsRef>()
  const sqUnitRef = useRef<ILawsRef>()
  const [unitId, setUnitId] = useState<string>('')
  const [sqUnitId, setSqUnitId] = useState<string>('')
  /**
   * !添加矛盾纠纷
   */
  const { mutateAsync: addMutation, isLoading: addIsLoading } = useAddBeef()
  /**
   * !修改矛盾纠纷
   */
  const { mutateAsync: updateMutation, isLoading: UIsLoading } =
    useUpdateBeefById()
  //根据当事人id获取当事人列表
  const { mutateAsync: getDsrList } = useGetById()
  //删除当事人列表
  const { mutateAsync: deleteDsr } = useRemoveById()
  //根据矛盾数据id获取当事人列表
  const { mutateAsync: getDsrListByBeefId } = useGetByBeefId()
  //获取所有的事件类型
  const { data: dataSource } = useGetAllBeefTypeMap()
  //图片附件的引用
  const imageRef = useRef<IUploadImgRefHandler>()
  //走访图片附件
  const imageRefZf = useRef<IUploadImgRefHandler>()
  //矛盾纠纷类型的引用
  const beefTypeRef = useRef<IRoleRestFillRefHandler>()

  //类型,控制表单矛排信息隐藏展示
  const [beefSource, setBeefSource] = useState<number>(1)
  //租户,控制表单矛排信息隐藏展示
  const [isZu, setIsZu] = useState<number>(1)
  const [openDsr, setOpenDsr] = useState<boolean>(false)
  // 当事人
  const DsrFormRef = useRef<IFormRef>()
  // 返回的当事人id
  const [dsrId, setDsrId] = useState<string[]>([])
  // 当事人数组
  const [dsrList, setDsrList] = useState<any>([])
  // 当事人查看修改
  //返回的类型数组
  const [typeList, setTypeList] = useState<
    {
      value: string
      label: string
    }[]
  >([])
  setTimeout(() => {
    if (props.isEdit == 0) {
      form.resetFields()
    }
  }, 500)

  // 当事人的数据
  const [dsrData, setDsrData] = useState<any>({})
  // 控制当事人弹窗的变量
  const [visibleDsr, setVisibleDsr] = useState<number>(0)
  useEffect(() => {
    if (beef) {
      console.log('进来了', beef)

      // setBeefSource(beef.beefSource)
      setIsZu(beef.isZu)
      unitRef.current?.fill(beef.unitId)
      if (beef.imgUrls) {
        imageRef.current?.fill(beef.imgUrls)
      }
      if (beef.zfImages) {
        imageRefZf.current?.fill(JSON.parse(beef.zfImages))
      }
      beefTypeRef.current?.fill(beef.beefType)
      form.setFieldsValue({
        isZu: beef.isZu,
        beefName: beef.beefName,
        beefType: beef.beefType,
        belongNetwork: beef.belongNetwork,
        riskLevel: beef.riskLevel,
        beefTime: dayjs(beef.beefTime),
        beefSource: beef.beefSource,
        beefAddress: beef.beefAddress,
        involveUnit: beef.involveUnit,
        involveCount: beef.involveCount,
        involveType: beef.involveType,
        eventScale: beef.eventScale,
        beefDetail: beef.beefDetail,
      })
      if (beef.unitId) {
        setUnitId(beef.unitId)
      }
      setSqUnitId(beef.sqUnitId)
      if (beef.beefLitigants && beef.beefLitigants.length > 0) {
        console.log(beef.beefLitigants, 'beef.beefLitigants')
        setDsrId([])

        beef.beefLitigants.forEach((item: any) => {
          setDsrId((prevIds) => [...prevIds, item.id])
        })

        // getDangList()
      } else {
        getBeefDsr()
      }
    }
  }, [beef])
  useEffect(() => {
    console.log(dsrId, 'dsrId')

    if (dsrId && dsrId.length > 0) {
      getDangList()
    }
  }, [dsrId])
  useEffect(() => {
    const arr: {
      value: string
      label: string
    }[] = []
    if (dataSource && dataSource.length > 0) {
      dataSource.forEach((item: any, index: any) => {
        arr.push({
          value: index,
          label: item,
        })
      })
      setTypeList(arr)
    }
  }, [dataSource])

  const getDangList = async () => {
    console.log('111111111111')

    if (dsrId && dsrId.length > 0) {
      // setDsrList([])
      //   dsrId.forEach(async (id: any) => {
      //     const res = await getDsrList({ id: id })
      //     setDsrList((parlist: any) => [...parlist, res])
      //   })
      const promises = dsrId.map(async (id: any, index: number) => {
        const res: any = await getDsrList({ id: id })
        return { ...res, key: index }
      })

      const results = await Promise.all(promises)
      const dsrList = results.map((result, index) => ({
        ...result,
        key: index, // 添加一个唯一的key属性
      }))
      setDsrList(dsrList)
      // setDsrList(results);
    }
  }
  const getBeefDsr = async () => {
    if(beef?.beefId){
    const res: any = await getDsrListByBeefId({ beefId: beef?.beefId })
    setDsrId([])
    res?.forEach((item: any) => {
      setDsrId((prevIds: any) => [...prevIds, item.id])
    })
    }

  }
  /**
   * 更新方法
   */
  const updateHandler = async () => {
    //设置图片
    form.setFieldValue('imgUrls', imageRef.current?.getUrls())
    form.setFieldValue(
      'zfImages',
      JSON.stringify(imageRefZf.current?.getUrls())
    )
    form.setFieldsValue({ litigantIdList: dsrId })

    const values = await form.getFieldsValue()

    await updateMutation({
      beefId: beef?.beefId,
      ...values,
      beefTime: dayjs(values.beefTime).format('YYYY-MM-DD HH:mm:ss'),
    })
    props.refetch?.()
    props.openFn(false)
    form.resetFields()
    // imageRef.current?.rest()
    // beefTypeRef.current?.rest()
    // unitRef.current?.rest()
    // sqUnitRef.current?.rest()
  }

  /**
   * 保存方法
   */
  const saveHandler = async () => {
    //设置图片
    // form.setFieldValue("imgUrls", imageRef.current?.getUrls());
    // form.setFieldValue("zfImages", JSON.stringify(imageRefZf.current?.getUrls()));
    const isPass = await form.validateFields()
    if (!isPass) {
      return
    }
    form.setFieldsValue({ litigantIdList: dsrId })
    const values = await form.getFieldsValue()
    await addMutation({
      ...values,
      beefTime: dayjs(values.beefTime).format('YYYY-MM-DD HH:mm:ss'),
    })
    props.refetch?.()
    props.openFn(false)
    form.resetFields()
    // imageRef.current?.rest();
    // beefTypeRef.current?.rest();
    // unitRef.current?.rest();
    // sqUnitRef.current?.rest();
  }
  const removeDsr = (id: string) => {
    Modal.confirm({
      title: '⚠️警告 你确删除该当事人吗',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        console.log('删除', id)
        await deleteDsr({ id: id })
        setDsrId(dsrId.filter((item) => item !== id))
      },
    })
  }
  /**
   * 向外暴露表单的保存和修改
   */
  useImperativeHandle(onRef, () => ({
    reset: () => {
      form.resetFields()
    },
    save: () => {
      saveHandler()
    },
    update: async () => {
      updateHandler()
    },
  }))

  const sqSelectHandlerChange = useCallback((val: string) => {
    form.setFieldValue('sqUnitId', val)
  }, [])

  const pcsSelectHandlerChange = useCallback((val: string) => {
    console.log('选择框', val)

    form.setFieldValue('unitId', val)
    setUnitId(val)
    sqUnitRef.current?.rest()
  }, [])

  const beefTypeHandlerChange = (val: number) => {
    form.setFieldValue('beefType', val)
  }
  // 打开当事人单位弹窗
  const DsrOpenFn = useCallback((open: boolean) => {
    setOpenDsr(open)
  }, [])
  //获取当事人的id
  const getDsrId = useCallback((val: string) => {
    // form.setFieldValue("litigantIdList", [...form.getFieldValue('litigantIdList'), val])
    setDsrId((prevState) => [...prevState, val])
  }, [])
  /**
   * 上传走访图片回调
   * @param url
   */
  const getUrlHandlerZf = (url: string) => {
    form.setFieldValue('zfImages', url)
  }
  /**
   * 上传矛盾图片的回调
   * @param url
   */
  const getUrlHandler = (url: string) => {
    form.setFieldValue('imgUrls', url)
  }
  const columns = [
    {
      title: '姓名',
      dataIndex: 'litigantName',
    },
    {
      title: '性别',
      dataIndex: 'gender',
    },
    {
      title: '身份证号',
      dataIndex: 'cardNumber',
    },
    {
      title: '操作',
      render: (project: any) => (
        <Space>
          {
            props.isEdit == 1?
            <Button
            onClick={() => {
              DsrOpenFn(true), setDsrData(project), setVisibleDsr(1)
            }}
          >
            查看
          </Button> :
            <>
                <Button
                    onClick={() => {
                      removeDsr(project.id)
                    }}
                  >
                    删除
                  </Button>
                  <Button
                    onClick={() => {
                      DsrOpenFn(true), setDsrData(project), setVisibleDsr(2)
                    }}
                  >
                    修改
                </Button></>

          }


          {/* <Button onClick={()=>{DsrOpenFn(true),setDsrData(project),setVisibleDsr(true)}}>查看</Button> */}
        </Space>
      ),
    },
  ]
  return (
    <Drawer
      title={props.isEdit == 0 ? '添加' : props.isEdit == 1 ? '查看' : '修改'}
      placement="right"
      width={'40rem'}
      closable={true}
      onClose={() => {
        props.openFn(false)
        setDsrId([])
        setDsrList([])
        props.setUpdate(undefined)
      }}
      forceRender={true}
      open={props.open}
      footer={
        <>
          {props.isEdit == 2 ? (
            <Button
              onClick={() => {
                updateHandler()
              }}
            >
              修改
            </Button>
          ) : props.isEdit == 0 ? (
            <Button
              onClick={() => {
                saveHandler()
              }}
            >
              保存
            </Button>
          ) : (
            <Button onClick={()=>{props.openFn(false)}}>关闭</Button>
          )}
        </>
      }
    >
      <Spin spinning={addIsLoading || UIsLoading}>
        {props.isEdit == 0 || props.isEdit == 2 ? (
          <Button
            style={{ marginBottom: '1rem' }}
            onClick={() => {
              DsrOpenFn(true), setVisibleDsr(0)
            }}
          >
            添加当事人
          </Button>
        ) : null}
        <TableContainer>
          <Table
            dataSource={dsrList}
            columns={columns}
            rowKey={(row) => row?.beefId}
          />
        </TableContainer>
        <DsrFrom
          handDsrId={getDsrId}
          openDsr={openDsr}
          onRef={DsrFormRef}
          openFn={DsrOpenFn}
          dsrData={dsrData}
          visibleDsr={visibleDsr}
          setVisibleDsr={setVisibleDsr}
          getDangList={getDangList}
          beefId={beef?.beefId}
        ></DsrFrom>
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item label={''} name={'litigantIdList'}>
            {/* <UnitSelect handleChange={pcsSelectHandlerChange} unitType={2} onRef={unitRef} /> */}
          </Form.Item>
          <Form.Item
            label={'申请类型'}
            name={'beefSource'}
            rules={[{ required: true, message: '事件类别不能为空' }]}
          >
            <Select
              options={[
                { value: 1, label: '110警情' },
                { value: 2, label: '矛盾纠纷自排查' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label={'事件类别'}
            name={'beefType'}
            rules={[{ required: true, message: '事件类别不能为空' }]}
          >
            <Select options={typeList} />
          </Form.Item>
          <Form.Item
            label={'事件名称'}
            name={'beefName'}
            rules={[{ required: true, message: '事件名称不能为空' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={'归属网络'}
            name={'belongNetwork'}
            rules={[{ required: true, message: '归属网络不能为空' }]}
          >
            <Select
              options={[
                { value: '网络一', label: '网络一' },
                { value: '网络二', label: '网络二' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label={'风险等级'}
            name={'riskLevel'}
            rules={[{ required: true, message: '风险等级不能为空' }]}
          >
            <Select
              options={[
                { value: '1', label: '一般类' },
                { value: '2', label: '关注类' },
                { value: '3', label: '重点类' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label={'发生时间'}
            name={'beefTime'}
            rules={[{ required: true, message: '发生时间不能为空' }]}
          >
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label={'详细地址'} name={'beefAddress'}>
            <Input />
          </Form.Item>
          <Form.Item label={'涉及单位'} name={'involveUnit'}>
            <Input />
          </Form.Item>
          <Form.Item label={'涉及人数'} name={'involveCount'}>
            <Input />
          </Form.Item>
          <Form.Item label={'涉湖类型'} name={'involveType'}>
            <Select
              options={[
                { value: '瑶湖', label: '瑶湖' },
                { value: '艾溪湖', label: '艾溪湖' },
              ]}
            />
          </Form.Item>
          <Form.Item label={'事件规模'} name={'eventScale'}>
            <Select
              options={[
                { value: '大型', label: '大型' },
                { value: '中型', label: '中型' },
                { value: '小型', label: '小型' },
              ]}
            />
          </Form.Item>
          <Form.Item label={'事件描述及诉求'} name={'beefDetail'}>
            <TextArea rows={4} placeholder="填写描述及诉求" />
          </Form.Item>
        </Form>
      </Spin>
    </Drawer>
  )
}

export default memo(BeefForm)
